# -*- coding: utf8 -*-
import re
import common
from BeautifulSoup import BeautifulSoup

site_index = 'kasi_time'
site_keyword = 'kasi-time'
site_url = 'http://www.kasi-time.com/'
test_url = 'http://www.kasi-time.com/item-262.html'

def get_lyric(url):
    prefix = 'http://www.kasi-time.com/item_js.php?no='
    pattern = 'item-([0-9]+)\.html'

    bool = re.compile(pattern).search(url)

    if bool:
        id = bool.group(1)
        full_url = prefix + id
        
        # get data
        try:
            data = common.get_url_content(full_url)
        except IOError:
            raise

        lyric = unicode(data, 'euc_jp')
        lyric = lyric.replace("document.write('", "")
        lyric = lyric.replace("');", "")
        lyric = lyric.replace("<br>", "\n")
        lyric = lyric.replace("&nbsp;", " ")
        lyric = re.sub(r'\\(.)', r'\1', lyric) # as stripslashes() in PHP
        lyric = lyric.strip()


        # test for half to full
        lyric = common.half2full(lyric)


        song_info = _get_song_info(url)
        lyric = song_info + lyric
            
        return lyric

    return None

def _get_song_info(url):
    data = common.get_url_content(url)

    encoding = 'euc_jp'
    data = data.decode(encoding, 'ignore')
    
    soup = BeautifulSoup(data)

    lines = []

    # category (may be blank)
    category = soup.find('td', {'class': 'td2'})
    key = category.string

    sibling = category.findNextSibling('td')
    if sibling.a:
        sakuhin = sibling.a.string
        type = sibling.a.nextSibling.strip()
        lines.append(u'%s %s\n' % (sakuhin, type))
    else:
        value = None
    
    # title
    heading = soup.find('h1')
    lines.append(u'%s\n' % (heading.string, ))

    # artist, lyric, music, arrangement
    infos = soup.findAll('td', {'class': 'td1'})
    for info in infos:
        key = info.string

        sib = info.findNextSibling('td')

        # combine all then strip HTML tags
        raw = [x.string for x in sib.contents] 
        raw = ''.join(raw)
        value = re.sub(r'<[^>]+>', '', raw)

        if value:
            lines.append(u'%s：%s' % (key, value))

    lines.append('\n\n')

    string = '\n'.join(lines)

    return string
